<?php
/**
 * 考场管理
 * @since   2018-06-14
 * @author  winljm001 <winljm001@126.com>
 */

namespace app\admin\controller;



use app\model\AdminExaminationRoom;
use app\model\AdminTestPersonnel;
use app\model\AdminTestPaper;
use app\model\AdminAcademicRecords;
use app\util\ReturnCode;
use app\util\Tools;

class ExaminationRoom extends Base {

    /**
     * 获取考场列表
     * @return array
     * @throws \think\exception\DbException
     * @author  winljm001 <winljm001@126.com>
     */
    public function index() {

        $limit = $this->request->get('size', config('apiAdmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $keywords = $this->request->get('keywords', '');
        $status = $this->request->get('status', '');
        $startTime = $this->request->get('startTime', '');
        $endTime = $this->request->get('endTime', '');
        $where = [];
        if($startTime!=''){
            $where['a.examStartTime'] = ['gt', $startTime];
        }
        if($endTime!=''){
            $where['a.examEndTime'] = ['lt', $endTime];
        }
        if ($status === '1' || $status === '0') {
            $where['a.status'] = $status;
        }
        
        if($keywords!=''){
            $where=array_merge($where,['a.id|a.name|e.name'=>['like', "%{$keywords}%"]]);
        }
        $listObj=(new AdminExaminationRoom())->alias('a')
        ->join('admin_test_paper e','a.testPaperId = e.id')
        ->field('a.*,e.name as testPaperName,e.passScore')
        ->where($where)->order('a.updateTime DESC')
        ->paginate($limit, false, ['page' => $start])->toArray();
        $where1=[];
        foreach ($listObj['data'] as $key => $value) {
            $where1['examinationRoomId'] = $value['Id'];
            $testPersonnelArr=db('admin_test_personnel')->where($where1)->select();
                // var_dump($testPersonnelArr);
            foreach ($testPersonnelArr as $k => $v) {
                $where2=[];
                $where2['testPersonnelId'] = $v['Id'];
                $AcademicRecordsArr=(new AdminAcademicRecords())->where($where2)->order('addTime DESC')->find();
                $testPersonnelArr[$k]['grade']=$AcademicRecordsArr['grade'];
            }
            $listObj['data'][$key]['testPersonnel']=$testPersonnelArr;

        }
        $listInfo = $listObj['data'];
        return $this->buildSuccess([
            'list'  => $listInfo,
            'count' => $listObj['total']
        ]);
    }

    /**
     * 新增考场
     * @return array
     * @author  winljm001 <winljm001@126.com>
     */
    public function add() {
        $postData = $this->request->post();
        $postData['addTime'] = time();
        $postData['updateTime'] = time();
        $res = AdminExaminationRoom::create($postData)->toArray();
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([
                'examinationRoomId'  => $res['Id']
            ]);
        }
    }

    /**
     * 删除考场
     * @return array
     * @author winljm001 <winljm001@126.com>
     */
    public function del() {
        $id = $this->request->get('id');
        if (!$id) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        AdminExaminationRoom::destroy($id);
        return $this->buildSuccess([]);
    }

    /**
     * 获取考场
     * @return object
     * @author winljm001 <winljm001@126.com>
     */
    public function getDetail() {
        $id = $this->request->get('id');
        if (!$id) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        $data = AdminExaminationRoom::get(['id' => $id]);
        $where1=[];
        $where1['examinationRoomId'] = $id;
        $testPersonnelArr=db('admin_test_personnel')->where($where1)->select();
        $data['testPersonnelNum']=count($testPersonnelArr);
        if($data['examStartTime']>time()){
           $data['examStatusStr']="未开始"; 
        }else{
            if($data['examStartTime']<time()&&$data['examEndTime']>time()){
                $data['examStatusStr']="考试中"; 
            }else{
                $data['examStatusStr']="已结束"; 
            }
            
        }
        return $this->buildSuccess([
            'examinationRoom'  => $data
        ]);
    }

    /**
     * 编辑考场
     * @author winljm001 <winljm001@126.com>
     * @return array
     * @throws \think\exception\DbException
     */
    public function edit() {
        $postData = $this->request->post();
        $postData['updateTime'] = time();
        $res = AdminExaminationRoom::update($postData);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([]);
        }
    }

    /**
     * 考场状态编辑
     * @return array
     * @author winljm001 <winljm001@126.com>
     */
    public function changeStatus() {
        $idArr = explode(',',$this->request->get('id'));
        if ($idArr[0]== '') {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '缺少必要参数');
        }
        $status = $this->request->get('status');
        foreach ($idArr as $key => $value) {
            $res = AdminExaminationRoom::update([
                'Id'         => $value,
                'status'     => $status
            ]);
        }
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([]);
        }
    }

    /**
     * 前台获取考生可参加考场
     * @return array
     * @author winljm001 <winljm001@126.com>
     */
    public function examineeERoomList() {
        $id = $this->request->post('id');
        if ($id== '') {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '缺少必要参数');
        }
        $where=[];
        $where['a.examineeId']=$id;
        $where['b.examEndTime'] = ['gt', time()];

        $listObj=(new AdminTestPersonnel())->alias('a')
        ->join('admin_examination_room b','b.id = a.examinationRoomId')
        ->join('admin_test_paper c','c.id = b.testPaperId')
        ->join('admin_academic_records d','d.testPersonnelId = a.id','LEFT')
        ->field('a.id as testPersonnelId,b.*,c.name as testPaperName,c.duration,c.totalPoints,c.id as testPaperId,d.id as academicRecordsId')
        ->group('b.id')
        ->where($where)->order('a.updateTime DESC')
        ->select();
        return $this->buildSuccess([
            'list'  => $listObj
        ]);
    }

    /**
     * 考生是否已经考试完毕
     * @return array
     * @author winljm001 <winljm001@126.com>
     */
    public function examineeIsTested() {
        $id = $this->request->post('id');
        if ($id== '') {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '缺少必要参数');
        }
        $where=[];
        $where['a.id']=$id;
        $obj=(new AdminTestPersonnel())->alias('a')
        ->join('admin_academic_records d','d.testPersonnelId = a.id','LEFT')
        ->field('a.id as testPersonnelId,d.id as academicRecordsId')
        ->group('a.id')
        ->where($where)
        ->find();
        if(empty($obj['academicRecordsId'])){
            $result=false;
        }else{
            $result=true;
        }
        return $this->buildSuccess([
            'isTested'  => $result
        ]);
    }
    /**
     * 前台获取考生已考考场
     * @return array
     * @author winljm001 <winljm001@126.com>
     */
    public function examineeERoomList2() {
        $id = $this->request->post('id');
        if ($id== '') {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '缺少必要参数');
        }
        $where=[];
        $where['a.examineeId']=$id;
        $where['b.examEndTime'] = ['lt', time()];

        $listObj=(new AdminTestPersonnel())->alias('a')
        ->join('admin_examination_room b','b.id = a.examinationRoomId')
        ->join('admin_test_paper c','c.id = b.testPaperId')
        ->join('admin_academic_records d','d.testPersonnelId = a.id','LEFT')
        ->field('a.id as testPersonnelId,b.*,c.name as testPaperName,c.duration,c.totalPoints,c.id as testPaperId,d.id as academicRecordsId')
        ->group('a.id')
        ->where($where)->order('a.updateTime DESC')
        ->select();
        return $this->buildSuccess([
            'list'  => $listObj
        ]);
    }
    
}
